<template>
  <div>
    <a-modal
      :visible="props.visible"
      title="添加商品"
      @ok="submit"
      @cancel="closeAddOne"
    >
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="商品名称">
          <a-input v-model:value="addForm.name" />
        </a-form-item>
        <a-form-item label="商品价格">
          <a-input-number
            v-model:value="addForm.price"
            :min="0"
            :max="999999"
          />
        </a-form-item>
        <a-form-item label="商家">
          <a-input v-model:value="addForm.merchant" />
        </a-form-item>
        <a-form-item label="分类">
          <a-select v-model:value="addForm.classify">
            <a-select-option
              v-for="item in classifyList"
              :key="item._id"
              :value="item._id"
              >{{ item.title }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item label="发布时间">
          <a-date-picker v-model:value="addForm.publishDate" />
        </a-form-item>
        <a-form-item label="库存">
          <a-input-number
            v-model:value="addForm.count"
            :min="1"
            :max="999999"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import { defineComponent, reactive } from 'vue'
import { deepClone, handleResult } from '../../helpers/utils'
import { goodService } from '../../services'
export default defineComponent({
  props: {
    visible: Boolean,
    classifyList: Array
  },
  setup (props, ctx) {
    /** 默认空表单数据 */
    const defaultForm = {
      name: '',
      price: 0,
      merchant: '',
      publishDate: 0,
      classify: '',
      count: 1
    }

    /** 添加商品表单数据 */
    const addForm = reactive(deepClone(defaultForm))

    /** 提交添加商品表单时事件 */
    const submit = async () => {
      const fromataddForm = deepClone(addForm)
      // 发布时间从moment对象转换成时间戳
      fromataddForm.publishDate = addForm.publishDate.valueOf()
      const res = await goodService.addGood(fromataddForm)
      handleResult(res).success(({ msg }) => {
        // 清空表单
        Object.assign(addForm, defaultForm)
        message.success(msg)
      })
    }

    /** 关闭添加商品弹框 */
    const closeAddOne = () => {
      ctx.emit('update:visible', false)
    }

    return {
      addForm,
      submit,
      props,
      closeAddOne
    }
  }
})
</script>

<style lang="scss" scoped></style>
